package com.zhlq.auth.tree.ctrl.annotation;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhlq.auth.function.bean.Function;
import com.zhlq.auth.resource.bean.Resource;
import com.zhlq.auth.resource.bean.ResourceForm;
import com.zhlq.auth.restype.bean.ResourceType;
import com.zhlq.auth.tree.bean.Node;
import com.zhlq.auth.tree.bean.TemplateTree;
import com.zhlq.auth.tree.bean.TemplateTreeRoleFunc;
import com.zhlq.auth.tree.bean.Tree;
import com.zhlq.auth.tree.bean.TreeForm;
import com.zhlq.auth.tree.service.TreeService;
import com.zhlq.condition.Query;
import com.zhlq.condition.Where;
import com.zhlq.constant.CtrlConstant;
import com.zhlq.page.Page;
import com.zhlq.tips.constant.TipsConstant;
import com.zhlq.util.CollectionUtil;
import com.zhlq.validator.bean.Validator;

@Controller
public class RoleFuncCtrl {

	private static final String AUTH_TREE_ROLE_PLUS = "auth/tree/rolefunc/plus";

	private static final String AUTH_TREE_ROLE_QUERY = "auth/tree/role/query";

	private static final String AUTH_TREE_ROLE_LIST = "auth/tree/rolefunc/list";

	private static final String NAME = "ROLE";

	private static final String SUBTREE = "ROLE_FUNC";

	@Autowired
	private TreeService treeService;
	@Autowired
	@Qualifier("roleTreeValidator")
	private RoleTreeValidator validatorService;

	@RequestMapping(AUTH_TREE_ROLE_LIST)
	public String list(HttpServletRequest request, HttpServletResponse response,
			Page page, TreeForm treeForm) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(
				validatorService.get(RoleTreeValidator.ROLE_TREE_LIST), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		
		// 角色功能树
		TemplateTreeRoleFunc authTree = treeService.getTemplateTreeRoleFunc(NAME, SUBTREE);
		List<TreeForm> authTreeList = treeService.getTreeFormRoleFunc(authTree, NAME, SUBTREE);
		request.setAttribute("authTreeList", authTreeList);

		// 当前节点
		TemplateTree currentNode = treeService.getCurrentNodeRoleFuncs(authTree, treeForm.getId());
		request.setAttribute("currentNode", currentNode);
		
		// 当前节点的所有子资源节点
		List<Node> childNodes = null==currentNode?new ArrayList<Node>():currentNode.getChildren();
		if(!CollectionUtil.isEmptyOrNull(childNodes)){
			request.setAttribute("childNodes", childNodes);				
		}

		// 当前节点的所有子功能节点
		if(null!=currentNode && currentNode instanceof TemplateTreeRoleFunc){
			TemplateTreeRoleFunc tmp = (TemplateTreeRoleFunc) currentNode;
			List<TemplateTreeRoleFunc> childFuncNodes = null==tmp?new ArrayList<TemplateTreeRoleFunc>():tmp.getSubtree();
			if(!CollectionUtil.isEmptyOrNull(childNodes)){
				request.setAttribute("childFuncNodes", childFuncNodes);				
			}
		}

		// 当前节点可选资源
		Where validateNodeWhere = new Where(Function.class);
//		validateNodeWhere.addIns("type", new Object[]{"0","1","2"});
		request.setAttribute("validateNodeResult", treeService.retrieves(validateNodeWhere, page));
		
		// 资源类型
		Where whereResourceType = new Where(ResourceType.class);
		request.setAttribute("resourceTypes", treeService.retrieve(whereResourceType));
		
		return AUTH_TREE_ROLE_LIST;
	}

//	@RequestMapping(AUTH_TREE_ROLE_QUERY)
	public String query(HttpServletRequest request, HttpServletResponse response,
			Page page, TreeForm treeForm) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(
				validatorService.get(RoleTreeValidator.ROLE_TREE_QUERY), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		
		// 功能资源树
		TemplateTree authTree = treeService.getTemplateTree(NAME);
		List<TreeForm> authTreeList = treeService.getTreeForm(authTree);
		request.setAttribute("authTreeList", authTreeList);

		// 资源树当前节点
		TemplateTree currentNode = treeService.getCurrentNode(authTree, treeForm.getId());
		request.setAttribute("currentNode", currentNode);
		
		// 资源树当前节点的所有子节点
		List<Node> childNodes = null==currentNode?new ArrayList<Node>():currentNode.getChildren();
		if(!CollectionUtil.isEmptyOrNull(childNodes)){
			request.setAttribute("childNodes", childNodes);				
		}

		// 当前节点可选资源
		ResourceForm resourceForm = treeForm.getResourceForm();
		if(null != resourceForm){
			Where validateNodeWhere = new Query(resourceForm).toWhere();
			validateNodeWhere.addIns("type", new Object[]{"0","1","2"});
			request.setAttribute("validateNodeResult", treeService.retrieves(validateNodeWhere, page));
			request.setAttribute("resourceForm", resourceForm);
		} else {
			Where validateNodeWhere = new Where(Resource.class);
			validateNodeWhere.addIns("type", new Object[]{"0","1","2"});
			request.setAttribute("validateNodeResult", treeService.retrieves(validateNodeWhere, page));
		}
		
		// 资源类型
		Where whereResourceType = new Where(ResourceType.class);
		request.setAttribute("resourceTypes", treeService.retrieve(whereResourceType));
		
		return AUTH_TREE_ROLE_LIST;
	}

//	@RequestMapping("auth/tree/role/add")
	public String add(HttpServletRequest request, HttpServletResponse response,
			TreeForm treeForm, RedirectAttributes attr) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(
				validatorService.get(RoleTreeValidator.ROLE_TREE_ADD), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 新的资源
		Resource resource = new Resource();
		resource.setEname(treeForm.getResource().getEname());
		resource.setCname(treeForm.getResource().getCname());
		resource.setType(treeForm.getResource().getType());
		// 保存到数据库
		treeService.create(resource);
		// 父节点
		Where parentWhere = new Where(TreeForm.class);
		parentWhere.add("id",null!=treeForm.getId()?treeForm.getId():0);
		TreeForm current = (TreeForm) treeService.retrieveOneForce(parentWhere);
		// 创建新的节点
		Tree tree = new Tree();
		if(null != current) {
			tree.setLevel(current.getLevel()+1);
			tree.setParentId(current.getId());
			tree.setResId(resource.getId());
			tree.setName(TreeForm.ROLE);
			// 资源树当前节点
			attr.addFlashAttribute(current);
		} else {
			tree.setLevel(0);
			tree.setParentId(0);
			tree.setResId(resource.getId());
			tree.setName(TreeForm.ROLE);
		}
		// 保存到数据库
		treeService.create(tree);
		return "redirect:/auth/tree/roleres/list.do";
	}

	@RequestMapping(AUTH_TREE_ROLE_PLUS)
	public String plus(HttpServletRequest request, HttpServletResponse response,
			Page page, TreeForm treeForm, RedirectAttributes attr) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(
				validatorService.get(RoleTreeValidator.ROLE_TREE_PLUS), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		
		// 资源
		Where resourceWhere = new Where(Resource.class);
		resourceWhere.addEqual("id", treeForm.getResId());
		Resource resource = (Resource) treeService.retrieveOneForceException(resourceWhere);
		
		// 当前点
		Where currentWhere = new Where(TreeForm.class);
		currentWhere.add("id",null!=treeForm.getId()?treeForm.getId():0);
		TreeForm currentNode = (TreeForm) treeService.retrieveOneForce(currentWhere);
		
		// 创建新的节点
		Tree tree = new Tree();
		if(null != currentNode) {
			tree.setLevel(currentNode.getLevel()+1);
			tree.setParentId(currentNode.getId());
			tree.setResId(resource.getId());
			tree.setName(SUBTREE);
			// 资源树当前节点
			attr.addFlashAttribute(currentNode);
			attr.addFlashAttribute(page);
			if(null != treeForm.getResourceForm()){
				attr.addFlashAttribute(treeForm.getResourceForm());
			}
		} else {
			tree.setLevel(0);
			tree.setParentId(0);
			tree.setResId(resource.getId());
			tree.setName(SUBTREE);
		}
		
		// 保存到数据库
		treeService.create(tree);
		return "redirect:/auth/tree/rolefunc/list.do";
	}

//	@RequestMapping("auth/tree/role/delete")
	public String delete(HttpServletRequest request, HttpServletResponse response,
			TreeForm treeForm) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(RoleTreeValidator.ROLE_TREE_DELETE_SUBTREE_FORCE), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		return "redirect:/auth/tree/function/list.do";
	}

//	@RequestMapping("auth/tree/role/delete/force")
	public String deleteForce(HttpServletRequest request, HttpServletResponse response,
			TreeForm treeForm) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(RoleTreeValidator.ROLE_TREE_DELETE_SUBTREE_FORCE), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		return "redirect:/auth/tree/roleres/list.do";
	}

//	@RequestMapping("auth/tree/role/delete/subtree")
	public String deleteSubtree(HttpServletRequest request, HttpServletResponse response,
			TreeForm treeForm) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(RoleTreeValidator.ROLE_TREE_DELETE_SUBTREE_FORCE), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		return "redirect:/auth/tree/function/list.do";
	}

//	@RequestMapping("auth/tree/role/delete/subtree/force")
	public String deleteSubtreeForce(HttpServletRequest request, HttpServletResponse response,
			TreeForm treeForm, RedirectAttributes attr) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(RoleTreeValidator.ROLE_TREE_DELETE_SUBTREE_FORCE), treeForm);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}

		// 父节点
//		Where parentWhere = new Where(TreeForm.class);
//		parentWhere.add("id", treeForm.getId());
//		TreeForm current = (TreeForm) treeService.retrieveOneException(parentWhere);
//		// 查询子树
//		TreeForm subTree = treeService.getSubTree(treeForm);
//		// 删除子树
//		treeService.deleteTree(subTree);
		// 资源树当前节点
//		attr.addFlashAttribute(current);
		return "redirect:/auth/tree/function/list.do";
	}
	
}
